#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "comfun/comfun_qt.h"
#include "../../STM32_Project/USER/comfun.h"

QSerialPort myserial;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(&myserial,&QSerialPort::readyRead,this,&MainWindow::on_serial_receive_data);
    on_pushButtonScan_clicked();
}

MainWindow::~MainWindow()
{
    delete ui;
}

QByteArray MainWindow::get_paras(QLineEdit *edit)
{
     QByteArray array;
     int i;
     unsigned int temp =edit->text().toUInt();
     for(i=0;i<4;i++)
     {
         array.append(char(temp>>(i*8)));
     }
     return array;
}

void MainWindow::on_serial_receive_data()
{
    QByteArray dataArray;
    dataArray = myserial.readAll();//读取数据    

    if(Qt::Checked == ui->checkBoxHexRece->checkState())
    {
        if(!dataArray.isEmpty())
        {
            char *data = dataArray.data();
            while (*data)
            {
                //hex + " "
                 ui->textEditRece->insertPlainText(QString::number(*data, 16).toUpper() + " ");
                 data++;
            }

//            QString str;
//            str = dataArray.toHex();//把数据直接转化为16进制的字符串形式
//            ui->textEditRece->insertPlainText(str + " ");
        }
    }
    else
    {
        ui->textEditRece->insertPlainText(dataArray);
    }

    QTextCursor cursor=ui->textEditRece->textCursor();
    cursor.movePosition(QTextCursor::End); //保持编辑器在光标最后一行
    ui->textEditRece->setTextCursor(cursor);


}

void MainWindow::serial_ui_init()
{

}
void MainWindow::on_pushButtonScan_clicked()
{
    ui->comboBox_portName->clear();
    ui->textEditRece->append("共扫描到 "
                              + QString::number(QSerialPortInfo::availablePorts().count())
                              + " 个可用串口：");


    foreach( const QSerialPortInfo &Info,QSerialPortInfo::availablePorts())//读取串口信息
    {
        qDebug() << "portName    :"  << Info.portName();//调试时可以看的串口信息
        qDebug() << "Description   :" << Info.description();
        qDebug() << "Manufacturer:" << Info.manufacturer();

        ui->textEditRece->append(Info.portName() +"  "+ Info.description());
        QSerialPort serial;
        serial.setPort(Info);
        ui->comboBox_portName->addItem( Info.portName()  );//在comboBox那添加串口号
    }
}

void MainWindow::on_pushButtonOpenSerial_clicked()
{
    myserial.setPortName(ui->comboBox_portName->currentText());//combo中选定的串口号
    myserial.setBaudRate((ui->comboBoxBaud->currentText()).toInt());
    myserial.setDataBits((enum QSerialPort::DataBits)(ui->comboBoxDataBits->currentText().toInt()));
    switch(ui->comboBoxStopBits->currentText().toInt())
    {
        case 1: myserial.setStopBits(QSerialPort::OneStop);break;
        case 3: myserial.setStopBits(QSerialPort::OneAndHalfStop);break;
        case 2: myserial.setStopBits(QSerialPort::TwoStop);break;
        default:qDebug()<<"停止位错误"; return;
    }
    switch(ui->comboBoxParity->currentIndex())
    {
        case 0: myserial.setParity(QSerialPort::NoParity);break;
        case 1: myserial.setParity(QSerialPort::OddParity);break;
        case 2: myserial.setParity(QSerialPort::EvenParity);break;
        default:qDebug()<<"校验位错误"; return;
    }

    myserial.setFlowControl(QSerialPort::NoFlowControl);//流控制

    if( myserial.isOpen() )
        myserial.close();
    else
        myserial.open(QIODevice::ReadWrite);//打开串口

    if( myserial.isOpen() )
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_opened_icon"));
        ui->pushButtonOpenSerial->setText("关闭串口");
    }
    else
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_closed_icon"));
        ui->pushButtonOpenSerial->setText("打开串口");
    }

    if(myserial.error())
    {
        QMessageBox::information(this, tr("提示"), tr("操作失败，请重试或者重启本软件！"));
        qDebug()<<"串口打开失败，原因是："<<myserial.error();
        myserial.clearError();
    }
}

void MainWindow::on_pushButtonSend_clicked()
{
    uint8_t buf[255] = {0};
    int data_len = 0;
    if( myserial.isOpen() )
    {
        if(Qt::Checked == ui->checkBoxHexSend->checkState())//hex send
        {
            QString str = ui->lineEditSend->text();
            QString temp_str ;//
            str.remove(QRegularExpression("[^0-9a-fA-F]"));//只保留HEX字符
            while(!str.isEmpty())
            {
                if(0!=(str.size()%2))
                {
                    qDebug()<<"字符为奇数";
                    return ;
                }
                temp_str = str.mid(0,510);
                data_len = hex_str_to_byte_arr(temp_str,buf,sizeof(buf),true);
                if(data_len > 0)
                {
                     myserial.write((char *)buf,data_len);
                }
                str.remove(0,510);
            }
        }
        else
        {
            myserial.write(ui->lineEditSend->text().toUtf8());//字符发送
        }
    }
    else
    {
        ui->textEditRece->append("串口未打开！");
    }

}

void MainWindow::on_pushButton_clicked()
{
    ui->textEditRece->setText("");
}



void MainWindow::on_pushButton_2_clicked()
{
      char buf[255] = {0};
      unsigned short crc;

      buf[0] = 0x68;//frame head
      QString data_str = ui->dataEdit->toPlainText();
      int data_len  =  hex_str_to_byte_arr(data_str,(uint8 *)(buf+8+1),sizeof(buf),true);
      if(-1 == data_len)
      {
          qDebug()<<"data wrong ";
          return ;
      }
      int pack_num = ui->lineEditPackNum->text().toInt();
      int_to_byte_arry(pack_num,buf+1);
      int_to_byte_arry(data_len,buf+4+1);

      crc = add_crc16((unsigned char *)buf,1+8+data_len);
      short_to_byte_arry(crc,buf+8+data_len+1);
      buf[8+data_len+2+1] = 0x16;//frame tail


      QString str,data_l =QString::number(data_len);
      byte_num_to_hex_string_with_space(str, buf, 1+8+data_len+2+1);

      ui->lineEditDataLen->setText(data_l);
      ui->lineEditUpdateFrame->setText(str);


}

void MainWindow::on_pushButton_3_clicked()
{
    uint8_t start_update_frame[] = {0x68,0x10,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,
                                    0x04,0x07,0xA1,0xAA,0x00,0x04,0x00,0x00,0x00,0x78,0x16 };

    if( myserial.isOpen() )
    {
        myserial.write((char *)start_update_frame,sizeof(start_update_frame));
    }
    else
    {
        ui->textEditRece->append("串口未打开！");
    }

}
